<template>
  <div class="box">
    <vxe-toolbar perfect>
      <template v-slot:buttons>
        <vxe-button @click="insertEvent(null)">新增</vxe-button>
        <vxe-button @click="$refs.xTable.removeCheckboxRow()">删除选中</vxe-button>
        <vxe-button @click="validEvent">校验</vxe-button>
        <vxe-button @click="fullValidEvent">完整校验</vxe-button>
        <vxe-button @click="selectValidEvent">选中校验</vxe-button>
      </template>
    </vxe-toolbar>

    <vxe-table  
      ref="xTable"
      border
      show-overflow
      keep-source
      highlight-cell
      class="my_table_insert"
      :data="tableData"
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell',showIcon: false ,showStatus: true,}"
      @edit-closed="editClosedEvent" 
    >
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column field="name" title="名称" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column field="role" title="职位" :edit-render="{name: 'input'}"></vxe-table-column>
      <!-- <vxe-table-column field="role" title="职位" :edit-render="{name: 'EditDownModal', props: {checkField: 'role'}}"></vxe-table-column> -->
      <vxe-table-column field="sex" title="Sex" :edit-render="{name: '$select',options: sexList}"></vxe-table-column>
      <vxe-table-column field="age" title="Age" :edit-render="{name: '$input', props: {type: 'integer'}}"></vxe-table-column>
      <vxe-table-column field="date" title="Date" :edit-render="{name: '$input', props: {type: 'date'}}"></vxe-table-column>
      <vxe-table-column title="操作" width="100" show-overflow>
        <template v-slot="{ row }">
          <!-- <vxe-button type="text" icon="fa fa-edit" @click="editEvent(row)"></vxe-button> -->
          <!-- <vxe-button type="text" status="danger" icon="fa fa-trash-o" @click="removeEvent(row)"></vxe-button> -->
          <vxe-button type="text" status="danger" icon="fa fa-trash-o" circle @click="removeEvent(row)">删除</vxe-button>
        </template>
      </vxe-table-column>
    </vxe-table>
  </div>
</template>

<script>
import tableData from './a.json'
import sexList from './sexList.json'
import VXETable from 'vxe-table'
export default {
  data() {
    const nameValid = ({ cellValue }) => {
      return new Promise((resolve, reject) => {
        if (cellValue.length < 3 || cellValue.length > 50) {
          reject(new Error('名称长度在 3 到 50 个字符之间'))
        } else {
          resolve()
        }
      })
    }
    const roleValid = ({ cellValue }) => {
      if (
        cellValue &&
        !['前端', '后端', '设计师', '项目经理', '测试'].includes(cellValue)
      ) {
        return Promise.reject(new Error('角色输入不正确'))
      }
    }
    VXETable.renderer.add('MyInput', {
      // 可编辑激活模板
      renderEdit (h, renderOpts, { row, column }) {
        return [
          <input class="my-cell" text="text" v-model={ row[column.property] } />
        ]
      },
      // 可编辑显示模板
      renderCell (h, renderOpts, { row, column }) {
        return [
          <span>{ row[column.property] }</span>
        ]
      }
    })
    return {
      tableData: tableData,
      sexList: sexList,
      validRules: {
        name: [
          { required: true, message: '名称必须填写' },
          { validator: nameValid }
        ],
        role: [{ validator: roleValid }],
        sex: [
          { required: true, message: '性别必须填写' },
          { pattern: /^[0,1]{1}$/, message: '格式不正确' }
        ],
        age: [{ pattern: '^[0-9]{0,3}$', message: '格式不正确' }]
      }
    }
  },
  created() {
    // this.tableData = window.MOCK_DATA_LIST.slice(0, 6)
  },
  methods: {
    async validEvent() {
      const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
      if (errMap) {
        this.$XModal.message({ status: 'error', message: '校验不通过！' })
      } else {
        this.$XModal.message({ status: 'success', message: '校验成功！' })
      }
    },
    async fullValidEvent() {
      const errMap = await this.$refs.xTable
        .fullValidate()
        .catch(errMap => errMap)
      if (errMap) {
        const msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            const { rowIndex, column, rules } = params
            rules.forEach(rule => {
              msgList.push(
                `第 ${rowIndex} 行 ${column.title} 校验错误：${rule.message}`
              )
            })
          })
        })
        this.$XModal.message({
          status: 'error',
          message: () => {
            return [
              <div class="red" style="max-height: 400px;overflow: auto;">
                {msgList.map(msg => (
                  <div>{msg}</div>
                ))}
              </div>
            ]
          }
        })
      } else {
        this.$XModal.message({ status: 'success', message: '校验成功！' })
      }
    },
    async selectValidEvent() {
      const selectRecords = this.$refs.xTable.getCheckboxRecords()
      console.log(selectRecords)
      if (selectRecords.length > 0) {
        const errMap = await this.$refs.xTable
          .validate(selectRecords)
          .catch(errMap => errMap)
        if (errMap) {
          this.$XModal.message({ status: 'error', message: '校验不通过！' })
        } else {
          this.$XModal.message({ status: 'success', message: '校验成功！' })
        }
      } else {
        this.$XModal.message({ status: 'warning', message: '未选中数据！' })
      }
    },
    async insertEvent(row) {
      // const xTable = this.$refs.xTable
      // const record = {}
      // xTable.insertAt(record, row).then(({ row }) => {
      //   xTable.setActiveRow(row)
      // })
      const record = {
        sex: '1'
      }
      const { row: newRow } = await this.$refs.xTable.insertAt(record, row)
      await this.$refs.xTable.setActiveCell(newRow, 'name')
    },
    async  editClosedEvent({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      const xTable = this.$refs.xTable
      const field = column.property
      const cellValue = row[field]
      // 判断单元格值是否被修改
      if (xTable.isUpdateByRow(row, field)) {
        const selectRecords = this.$refs.xTable.getActiveRecord().row
        const errMap = await this.$refs.xTable
          .validate([selectRecords])
          .catch(errMap => errMap)
        if (errMap) {
          this.$XModal.message({ status: 'error', message: '校验不通过！' })
        } else {
          // this.$XModal.message({ status: 'success', message: '校验成功！' })
          setTimeout(() => {
            this.$XModal.message({
              message: `局部保存成功！ ${field}=${cellValue}`,
              status: 'success'
            })
            // 局部更新单元格为已保存状态
            this.$refs.xTable.reloadRow(row, null, field)
          }, 300)
        }
      }
    },
    removeEvent (row) {
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        if (type === 'confirm') {
          this.$refs.xTable.remove(row)
        }
      })
    },
  }
}
</script>

<style lang="scss">
::v-deep .vxe-header--column {
  display: none !important;
}
</style>